package com.ruoyi.web.controller.finance;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.web.common.TypeNameEnum;
import com.ruoyi.web.dto.AccountDetailResp;
import com.ruoyi.web.dto.AddTallyReq;
import com.ruoyi.web.dto.BalanceDetailResp;
import com.ruoyi.web.entity.AccountInfo;
import com.ruoyi.web.entity.BalanceChangeDetail;
import com.ruoyi.web.entity.UserBalance;
import com.ruoyi.web.mapper.BalanceChangeDetailMapper;
import com.ruoyi.web.service.AccountInfoService;
import com.ruoyi.web.service.AssetService;
import com.ruoyi.web.service.UserBalanceService;
import com.ruoyi.web.util.LocalDateTimeUtils;
import com.ruoyi.web.util.OptionalUtils;
import com.ruoyi.web.util.PageUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 动账信息
 */
@Controller
@RequestMapping("/finance/dzxx")
public class DzxxController {

    @Resource
    private UserBalanceService userBalanceService;
    @Resource
    private AccountInfoService accountInfoService;
    @Resource
    private BalanceChangeDetailMapper balanceChangeDetailMapper;
    @Resource
    private AssetService assetService;

    @GetMapping()
    public String dzxx(Model modelAndView) {
        UserBalance wh = userBalanceService.selectByUser("文豪", LocalDateTime.now());
        UserBalance mm = userBalanceService.selectByUser("蒙蒙", LocalDateTime.now());
        UserBalance gt = userBalanceService.selectByUser("共同", LocalDateTime.now());


        BigDecimal whBalance = getBalanceFunction(wh);
        BigDecimal mmBalance = getBalanceFunction(mm);
        BigDecimal gtBalance = getBalanceFunction(gt);

        modelAndView.addAttribute("whBalance", whBalance.toPlainString());
        modelAndView.addAttribute("mmBalance", mmBalance.toPlainString());
        modelAndView.addAttribute("gtBalance", gtBalance.toPlainString());
        modelAndView.addAttribute("sumBalance", whBalance
                .add(mmBalance)
                .add(gtBalance)
                .toPlainString());

        AccountInfo currentAccount = accountInfoService.getCurrentAccount();
        if (currentAccount != null) {
            // 流动资金
            BigDecimal ldzjBalance = currentAccount.getLiquidity();
            modelAndView.addAttribute("ldzjBalance", ldzjBalance.toPlainString());

            // 总市值
            LocalDate dataDate = currentAccount.getDataDate();

            AccountDetailResp accountDetailResp = new AccountDetailResp();
            accountDetailResp.setDataDate(LocalDateTimeUtils.dateTime2DateString(dataDate));
            ArrayList<AccountDetailResp.AssetDetailResp> accountDetailList = Lists.newArrayList();
            accountDetailResp.setAssetDetailList(accountDetailList);

            for (TypeNameEnum typeNameEnum : TypeNameEnum.values()) {
                accountDetailList.addAll(assetService.calcAssetDetail(dataDate, typeNameEnum.getTypeName()));
            }


            AccountDetailResp.AssetDetailResp e = new AccountDetailResp.AssetDetailResp();
            e.setTypeName("流动资金");
            e.setMarketValue(currentAccount.getLiquidity().toPlainString());
            accountDetailList.add(e);

            AccountDetailResp.AssetDetailResp zsz = new AccountDetailResp.AssetDetailResp();
            zsz.setTypeName("总市值");
            zsz.setMarketValue(OptionalUtils.sum(accountDetailList, assetSummaryResp -> new BigDecimal(assetSummaryResp.getMarketValue()))
                    .toPlainString());
            accountDetailList.add(zsz);


            modelAndView.addAttribute("zszBalance", zsz.getMarketValue());
        }


        return "finance/dzxx/dzxx";
    }


    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list() {
        /*动账明细*/
        LambdaQueryWrapper<BalanceChangeDetail> queryWrapper = new QueryWrapper<BalanceChangeDetail>()
                .lambda()
                .orderByDesc(BalanceChangeDetail::getCreateTime);

        Page<BalanceChangeDetail> page = PageUtils.getPage();
        Page<BalanceChangeDetail> balanceChangeDetailPage = balanceChangeDetailMapper.selectPage(page, queryWrapper);

        if (CollectionUtils.isNotEmpty(balanceChangeDetailPage.getRecords())) {
            List<BalanceDetailResp> convert = convert(balanceChangeDetailPage.getRecords());
            Page<BalanceDetailResp> balanceDetailRespPage = PageUtils.copyProperties(balanceChangeDetailPage, convert);
            return PageUtils.page2Table(balanceDetailRespPage);
        }
        return PageUtils.page2Table(balanceChangeDetailPage);
    }


    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        return "finance/dzxx/add";
    }

    /**
     * 新增动账信息
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AddTallyReq addTallyReq) {
        try {
            userBalanceService.balanceBusiness(addTallyReq);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


    private BigDecimal getBalanceFunction(UserBalance userBalance) {
        if (userBalance == null) {
            return BigDecimal.ZERO;
        }
        return OptionalUtils.bigDecimalDefault(userBalance.getBalance());
    }

    private List<BalanceDetailResp> convert(List<BalanceChangeDetail> balanceChangeDetails) {
        return balanceChangeDetails.stream()
                .map(balanceChangeDetail -> {
                    BalanceDetailResp balanceDetailResp = new BalanceDetailResp();
                    balanceDetailResp.setCreateTime(LocalDateTimeUtils.dateTime2DateString(balanceChangeDetail.getCreateTime()));
                    balanceDetailResp.setTranType(balanceChangeDetail.getTranType());
                    balanceDetailResp.setAmount(balanceChangeDetail.getAmount().toPlainString());
                    balanceDetailResp.setUserName(balanceChangeDetail.getUserName());

                    UserBalance wh = userBalanceService.selectByUser("文豪", balanceChangeDetail.getCreateTime());
                    UserBalance mm = userBalanceService.selectByUser("蒙蒙", balanceChangeDetail.getCreateTime());
                    UserBalance gt = userBalanceService.selectByUser("共同", balanceChangeDetail.getCreateTime());

                    BigDecimal whBalance = getBalanceFunction(wh);
                    BigDecimal mmBalance = getBalanceFunction(mm);
                    BigDecimal gtBalance = getBalanceFunction(gt);

                    balanceDetailResp.setWh(whBalance.toPlainString());
                    balanceDetailResp.setMm(mmBalance.toPlainString());
                    balanceDetailResp.setGt(gtBalance.toPlainString());


                    balanceDetailResp.setRemark(balanceChangeDetail.getRemark());
                    if (balanceChangeDetail.getImageFile() != null) {
                        balanceDetailResp.setImageFile(new String(balanceChangeDetail.getImageFile()));
                    }

                    return balanceDetailResp;
                })
                .collect(Collectors.toList());
    }

}
